package 多线程.状态.停止线程;

/**
 * 不推荐使用stop()和destory()
 */
public class StopThread {
    public static void main(String[] args) throws InterruptedException {
        Sum sum = new Sum();
        Thread thread =new Thread(sum);
        thread.start();
        for(int i=0;i<50;i++){
            //System.out.println("main "+i);
            Thread.sleep(100);
            if(i==25){
                sum.stop();
                System.out.println("已经停止");
            }
        }
    }
}

class Sum implements Runnable{
    volatile   private boolean flag = false;
    int sum =0,i=0;
    @Override
    public void run() {
        while(flag==false){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sum+=i++;
            System.out.println("i="+i+",和为"+sum);
        }
        //System.out.println("i="+i+",和为"+sum);
    }
    public void stop(){
        flag=true;
    }
}
